package de.openkanban.server.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import de.openkanban.server.dao.HistoryDao;
import de.openkanban.server.domain.Board;
import de.openkanban.server.domain.History;
import de.openkanban.server.service.BoardService;
import de.openkanban.shared.util.HistoryAction;
import de.openkanban.shared.util.StatusCodes;

/**
 * jpa implementation of history data access object
 */
@Repository
public class HistoryDaoImpl implements HistoryDao {

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private BoardService boardService;

	@Override
	@Transactional
	public StatusCodes writeHistoryEntry(Long userId, Long parentActivityId, HistoryAction createKanban, String historyText) {
		Board parentBoard = boardService.getBoardByActivityIdLong(parentActivityId);
		return writeHistoryEntry(parentBoard.getBoardId(), userId, parentActivityId, createKanban, historyText);
	}

	@Override
	@Transactional
	public StatusCodes writeHistoryEntry(Long boardId, Long userId, Long activityId, HistoryAction historyAction, String text) {
		History newHistory = new History(userId, boardId, activityId, historyAction, text);
		entityManager.persist(newHistory);
		return StatusCodes.OK;
	}

	@Override
	@SuppressWarnings("unchecked")
	public History[] getFullBoardHistory(Long boardId) {
		Query query = entityManager.createQuery("SELECT h FROM History h WHERE h.boardId=:boardId");
		query.setParameter("boardId", boardId);
		return (History[]) query.getResultList().toArray(new History[] {});
	}

}
